from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class silhouettes(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)

        # R code for generating the coldiss plot
        self.R('source(\''+unicode(os.path.join(redREnviron.directoryNames['libraryDir'], 'ecology', 'widgets', 'silhouettes.R')).replace('\\', '//')+'\')')
        
        # Python variables
        self.data = {}
        self.RFunctionParam_object = ''
        self.RFunctionParam_diss = ''
        self.RFunctionParam_clust = ''
        
        #Inputs
        self.inputs.addInput('id0', 'Initial data (before dissimilarity)', signals.base.RDataFrame, self.processobject) 
        self.inputs.addInput('id1', 'Dissimilarity', signals.base.RMatrix, self.processdiss) # creer un signal pour dissimilarity object
        self.inputs.addInput('id2', 'Cluster analysis', signals.base.RList, self.processclust) # creer un signal pour cluster object
        
        #GUI
        self.RFunctionParam_GUI_tabs = redRGUI.base.tabWidget(self.controlArea)
        self.RFunctionParam_GUI_tabsWidth = self.RFunctionParam_GUI_tabs.createTabPage(name = "Silhouette widths",orientation='vertical')
        self.RFunctionParam_GUI_tabsFinal = self.RFunctionParam_GUI_tabs.createTabPage(name = "Silhouette final",orientation='vertical')
        self.RFunctionParam_widthType = redRGUI.base.radioButtons(self.RFunctionParam_GUI_tabsWidth,  label = "Optimisation", buttons = [('silhouette'), ('mantel')],
        setChecked='silhouette',orientation='horizontal')
        self.plotAreaWidth = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsWidth, label = "Silhouette widths: ", displayLabel = False)
        self.RFunctionParam_numClust = redRGUI.base.spinBox(self.RFunctionParam_GUI_tabsFinal, label='Number of clusters: ', min = 1,max=100, value = 4 )
        self.RFunctionParam_extWin = redRGUI.base.checkBox(self.RFunctionParam_GUI_tabsFinal, label='Plot options', buttons = [('plotExt', 'Plot in external window?')], setChecked=None)
        self.plotAreaFinal = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsFinal, label = "Silhouette final", displayLabel = False)
        
        #Plot area Final
        self.plotAreaFinal.optionWidgets['imageType'].setCurrentId('png') # set to png because silhouette plots are not plottable through svg
        self.plotAreaFinal.topArea.hide() # hide the graphic options bar
        
        #Commit
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)
        
        
    def processobject(self, data):
        if not self.require_librarys(["cluster"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_object=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_clust=''
            
    def processclust(self, data):
        if not self.require_librarys(["cluster"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_clust=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_clust=''

    def processdiss(self, data):
        if not self.require_librarys(["cluster"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_diss=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_diss=''
            
            
    def commitFunction(self):
        if unicode(self.RFunctionParam_object) == '':
            self.status.setText('No initial data.')
            return
        if unicode(self.RFunctionParam_clust) == '':
            self.status.setText('No cluster data.')
            return
        if unicode(self.RFunctionParam_diss) == '':
            self.status.setText('No dissimilarity data.')
            return

        self.plotAreaWidth.plotMultiple(query = 'x='+unicode(self.RFunctionParam_object)+', clust='+unicode(self.RFunctionParam_clust)+', dissimilarity='+unicode(self.RFunctionParam_diss)+',type="'+unicode(self.RFunctionParam_widthType.getChecked())+'"', function = 'silhouetteWidth')
        
        self.plotAreaFinal.plotMultiple(query = 'x='+unicode(self.RFunctionParam_object)+', clust='+unicode(self.RFunctionParam_clust)+', dissimilarity='+unicode(self.RFunctionParam_diss)+',numClust='+unicode(self.RFunctionParam_numClust.value()), function = 'silhouetteFinal')
        
        if 'plotExt' in self.RFunctionParam_extWin.getCheckedIds():
            self.R('silhouetteFinal(x='+unicode(self.RFunctionParam_object)+', clust='+unicode(self.RFunctionParam_clust)+', dissimilarity='+unicode(self.RFunctionParam_diss)+',numClust='+unicode(self.RFunctionParam_numClust.value())+')')
        
        
        
        